import re
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from django_redis import get_redis_connection
from user.models import User
from user.utils import get_user_by_account
from rest_framework_jwt.settings import api_settings


class UserModelSerializer(ModelSerializer):
    token = serializers.CharField(max_length=1024, read_only=True, help_text='用户token')
    code = serializers.CharField(write_only=True, help_text='手机验证码')

    class Meta:
        model = User
        fields = ('phone', 'password', 'id', 'username', 'token', 'code')

        extra_kwargs = {
            'phone': {
                'write_only': True
            },
            'password': {
                'write_only': True
            },
            "username": {
                "read_only": True,
            },
            "id": {
                "read_only": True,
            },
        }

    def validate(self, attrs):
        phone = attrs.get('phone')
        password = attrs.get('password')
        sms_code = attrs.get('code')

        if not re.match(r"^1[35678]\d{9}$", phone):
            raise serializers.ValidationError('手机号不合法')

        try:
            user = get_user_by_account(phone)
        except:
            user = None

        if user:
            raise serializers.ValidationError('该手机号已被注册')

        redis_connection = get_redis_connection('sms_code')
        mobile_code = redis_connection.get('mobile_%s' % phone)
        if mobile_code is None:
            raise serializers.ValidationError('验证码错误或已过期')
        if mobile_code.decode() != sms_code:
            raise serializers.ValidationError('验证码错误')
        return attrs

    def create(self, validated_data):
        password = validated_data.get('password')
        hash_password = make_password(password)
        username = validated_data.get('phone')
        user = User.objects.create(phone=username, username=username, password=hash_password)

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)

        return user


class PhoneLoginModelSerializer(ModelSerializer):
    phone = serializers.CharField(write_only=True)
    token = serializers.CharField(max_length=1024, read_only=True, help_text='用户token')
    code = serializers.CharField(write_only=True, help_text='手机验证码')

    class Meta:
        model = User
        fields = ('phone', 'id', "token", "code", 'username')

        extra_kwargs = {
            'id': {
                'read_only': True
            },
            'username': {
                'read_only': True
            }
        }

    def validate(self, attrs):
        phone = attrs.get('phone')
        sms_code = attrs.get('code')
        try:
            user = get_user_by_account(phone)
        except:
            user = None

        if user is None:
            raise serializers.ValidationError('该手机号还未注册,请前往注册')
        redis_connection = get_redis_connection("sms_code")
        mobile_code = redis_connection.get("mobile_%s" % phone)

        if mobile_code is None:
            raise serializers.ValidationError('验证码错误或已过期')

        if mobile_code.decode() != sms_code:
            raise serializers.ValidationError('验证码错误')
        user_obj = User.objects.filter(phone=phone).first()
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user_obj)
        token = jwt_encode_handler(payload)
        self.obj = user_obj
        self.token = token
        return attrs
